package com.aifast.gen.business.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.aifast.common.base.R;
import com.aifast.common.global.BusinessException;
import com.aifast.common.layui.LayuiDataTable;
import com.aifast.common.layui.LayuiPageFactory;
import com.aifast.gen.business.dao.GenTableColumnDao;
import com.aifast.gen.business.dao.GenTableDao;
import com.aifast.gen.business.entity.GenTable;
import com.aifast.gen.business.entity.GenTableColumn;
import com.aifast.gen.core.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 * 代码生成业务表 服务实现类
 * </p>
 *
 * @author fujian
 * @since 2022-05-23
 */
@Service
@RequiredArgsConstructor
public class GenTableService extends ServiceImpl<GenTableDao, GenTable> {

    private final GenTableDao dao;
    private final GenTableColumnDao genTableColumnDao;

    /**
     * layui数据表格列表查询方法
     * <br>这里参数不使用参数类，当超过5个参数时筛选条件参数建议使用参数类param封装
     *
     * @param search 关键字搜索
     * @param page   分页
     * @return 列表数据
     */
    public LayuiDataTable list(String search, Page page) {
        LambdaQueryWrapper<GenTable> wrapper = new LambdaQueryWrapper<GenTable>()
                .eq(StrUtil.isNotBlank(search), GenTable::getTableName, search)
                .orderByDesc(GenTable::getTableId);
        return LayuiPageFactory.init(page(page, wrapper));
    }

    /**
     * 新增或者修改
     * <br>vo的方法另写，里面有判定是否新增还是修改 可自定义逻辑
     *
     * @param genTable
     * @return
     */
    public Boolean insertOrUpdate(GenTable genTable) {
        if (ObjectUtil.isNull(genTable.getTableId())) {

        }
        return saveOrUpdate(genTable);
    }

    /**
     * 删除方法
     * <br>提供单个删除和批量删除
     *
     * @param id  数据id
     * @param ids 数据id集合
     * @return
     */
    public Boolean del(Integer id, String ids) {
        List<Integer> integers = new ArrayList<>();
        if (StrUtil.isNotBlank(ids)) {
            integers = Convert.toList(Integer.class, ids.split(","));
        }
        if (ObjectUtil.isNotNull(id)) {
            integers.add(id);
        }
        try {
            integers.forEach(i -> {
                boolean b = removeById(i);
                if(b){
                    genTableColumnDao.delete(new QueryWrapper<GenTableColumn>().eq("table_id",i));
                }
            });
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 数据详情
     *
     * @param id 数据id
     * @return
     */
    public R info(Integer id) {
        if (ObjectUtil.isNull(id)) return R.ERROR();
        GenTable one = getOne(new QueryWrapper<GenTable>().eq("table_id", id));
        return R.OK(one);
    }

    public LayuiDataTable dbList(String searchValue, Page page) {
        Page<GenTable> list = dao.dbList(searchValue, page);
        return LayuiPageFactory.init(list);
    }

    public R insertByTableName(String[] tableNames) {
        for (String table : tableNames) {
            GenTable genTable = dao.get(table);
            int insert = dao.insert(GenUtil.initTable(genTable));
            if (insert > 0) {
                List<GenTableColumn> tableColumns = genTableColumnDao.getTableColumns(table);
                int size = tableColumns.size();
                if (size == 0) {
                    break;
                }
                tableColumns.stream().map(i -> GenUtil.initColumnField(i, genTable)).forEach(genTableColumnDao::insert);
            }
        }
        return R.OK();
    }

    public LayuiDataTable tableColumnList(Integer tableId, Page page) {
        LambdaQueryWrapper<GenTableColumn> wrapper = new LambdaQueryWrapper<GenTableColumn>()
                .eq(ObjectUtil.isNotNull(tableId), GenTableColumn::getTableId, tableId)
                .orderByAsc(GenTableColumn::getColumnId);
        Page<GenTableColumn> list = genTableColumnDao.selectPage(page, wrapper);
        return LayuiPageFactory.init(list);
    }

    public void genCode(String tableName, HttpServletRequest request) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = dao.selectGenTableByName(tableName);

        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);
        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try
            {
                String path = getGenPath(table, template);
                FileUtils.writeStringToFile(new File(path), sw.toString(), "UTF-8");
            }
            catch (IOException e)
            {
                throw new BusinessException("渲染模板失败，表名：" + table.getTableName());
            }
        }

    }

    /**
     * 获取代码生成地址
     *
     * @param table 业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTable table, String template)
    {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/"))
        {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
        }
        return genPath + File.separator + VelocityUtils.getFileName(template, table);
    }

    private void setPkColumn(GenTable table) {
        for (GenTableColumn column : table.getColumns())
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(table.getColumns().get(0));
        }
        if (GenConstants.TPL_SUB.equals(table.getTplCategory()))
        {
            for (GenTableColumn column : table.getSubTable().getColumns())
            {
                if (column.isPk())
                {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (StringUtils.isNull(table.getSubTable().getPkColumn()))
            {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }

    }

    private void setSubTable(GenTable table) {
        String subTableName = table.getSubTableName();
        if (StrUtil.isNotBlank(subTableName)) {
            GenTable tmp = getOne(new QueryWrapper<GenTable>().eq("table_name", subTableName).last("limit 1"));
            List<GenTableColumn> tableColumns = genTableColumnDao.getTableColumns(subTableName);
            tmp.setColumns(tableColumns);
            table.setSubTable(tmp);
        }
    }


    public Object preview(Long tableId) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        GenTable table = dao.selectGenTableById(tableId);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        Console.log(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);
        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;

    }

    public boolean eidtTableColumn(GenTableColumn column) {
        if(ObjectUtil.isNull(column.getColumnId())){
            return false;
        }
        GenTableColumn tmp = genTableColumnDao.selectById(column.getColumnId());

        tmp.setJavaType(StrUtil.isNotBlank(column.getJavaType()) ? column.getJavaType() : null);
        tmp.setQueryType(StrUtil.isNotBlank(column.getQueryType()) ? column.getQueryType() : null);
        tmp.setHtmlType(StrUtil.isNotBlank(column.getHtmlType()) ? column.getHtmlType() : null);
        tmp.setIsRequired(StrUtil.isNotBlank(column.getIsRequired()) ? column.getIsRequired() : null);
        tmp.setIsInsert(StrUtil.isNotBlank(column.getIsInsert()) ? column.getIsInsert() : null);
        tmp.setIsList(StrUtil.isNotBlank(column.getIsList()) ? column.getIsList() : null);
        tmp.setIsEdit(StrUtil.isNotBlank(column.getIsEdit()) ? column.getIsEdit() : null);
        tmp.setIsQuery(StrUtil.isNotBlank(column.getIsQuery()) ? column.getIsQuery() : null);
        tmp.setDictType(StrUtil.isNotBlank(column.getDictType()) ? column.getDictType() : "");
        tmp.setGridType(StrUtil.isNotBlank(column.getGridType()) ? column.getGridType() : null);
        tmp.setColumnComment(StrUtil.isNotBlank(column.getColumnComment()) ? column.getColumnComment() : null);
        tmp.setJavaField(StrUtil.isNotBlank(column.getJavaField()) ? column.getJavaField() : null);
        return genTableColumnDao.updateById(tmp) > 0;

    }

    public byte[] downloadCode(String tableName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip)
    {
        // 查询表信息
        GenTable table = dao.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try
            {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, Constants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            }
            catch (IOException e)
            {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
            }
        }
    }
}
